﻿/*********************公用函数*********************/
function ltrim( str ){
	return str.replace(/^\s+/g,"")
};

function rtrim( str ){
	return str.replace(/^\s+$/g,"")
};

function trim( str ){
	return ltrim(rtrim(str));
};

/*智能计算字数chrome不能使用DOM3 KeyboardEvent是Webkit的bug,此函数从v.t.qq.com拷贝*/
function smartLen( str ){
	str = str.replace(urlreg,'填充填充填充填充填充填');
	return Math.ceil((trim(str.replace(/[^\u0000-\u00ff]/g,"aa")).length)/2);
};

/*智能截断字符串*/
function smartCut( str,maxlen ){
    if( smartLen(str) <= maxlen ){
       return str;
	}else{
		for( var i=0,l=str.length;i<l;i++ ){
			var temp = str.substr(0,i);
		    if( smartLen( temp ) >= maxlen ){
			    return temp;
			}
		}
		return str;//fail silently
	}
}

/*重新计算字数*/
function recountText(){
	var content = document.getElementById("textContent");
	var textLen = smartLen(content.value);
	var textLenDiv = document.getElementById("txtLen");
	if( (140-textLen)<0 ){//超出
		textLenDiv.innerHTML = '超出<em style="color:#E56C0A">'+(textLen-140)+'</em>字';
	}else{
		textLenDiv.innerHTML = '还能输入<em>'+(140-textLen)+'</em>字';
	}
}

/*********************页面逻辑*********************/

//插入到v.t.qq.com中的js
var loggedin = !!!document.getElementById("loginframe");
var hasvideo = !!document.getElementById("videoPat");
var haspic = !!document.getElementById("imgList");
//告诉登录态
var port = chrome.extension.connect({name:"quickshare"});
port.postMessage({pageReport:{
	isLogin:loggedin,
	hasVideo:hasvideo,
	hasPic:haspic
}})

//接收来自插件的消息
chrome.extension.onConnect.addListener(function(actionport){
	if(actionport.name != "quickshareaction"){ return; }
	actionport.onMessage.addListener(function(msg){
		if('buttonaction' in msg){
			handleButtonAction(msg.buttonaction);
		}else if('emoteaction' in msg){
			handleEmoteAction(msg.emoteaction);
		}
	});
});

//转播按钮动作
var postbtn = document.getElementById("postdata");
if(postbtn){
	postbtn.onclick = function(){
		port.postMessage({notification:"startPostData"});
        var freq = 3,//检查频率
            time = 0,
            maxWaitimgTime = 30*1000;//等待30秒后没有成功的消息即认为失败

        var checkMessageStatus = setInterval(function(){//检查数据是否发送成功
       
                 if( time > maxWaitimgTime){//超时即失败
                      port.postMessage({notification:"messageFailed"});
                      clearInterval(checkMessageStatus);
                      return;
                 }

                 if(!!document.getElementsByClassName("success")){//消息一定发送成功
                      port.postMessage({notification:"messageSuccess"});
                      clearInterval(checkMessageStatus);
                      return;
                 }

                 time+=1000/freq;

             },1000/freq);
	}
}


/*登录按钮动作*/
if(!loggedin){
	var loginbtn = document.getElementById("loginframe").contentDocument.getElementById("login_btn");
	if(loginbtn){
		loginbtn.onclick = function(){
			port.postMessage({notification:"startLogin"});
		}
	}
}

/*通用URL正则*/
var urlreg = new RegExp("((news|telnet|nttp|file|http|ftp|https)://){1}(([-A-Za-z0-9]+(\\.[-A-Za-z0-9]+)*(\\.[-A-Za-z]{2,5}))|([0-9]{1,3}(\\.[0-9]{1,3}){3}))(:[0-9]*)?(/[-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]*)*","gi");

/*去除URL尾巴,url字段会自动做为消息的一部分,与微博模板不符,因此去除该尾巴*/
(function(){
	var url = /&url=(.*)&appkey=/.exec(location.search)[1];
    url = decodeURIComponent(url);
	var content = document.getElementById("textContent");
	content.value = content.value.slice(0,-url.length-1/*url前面会自动加一个空格*/);
	recountText();
})();

/*根据URL分割字符串,返回ArrayLike字符串Obj*/
function splitByURL( str ){
    var strObj={}; 
    var index=0; 
    var count=0;
    var temp;
    while(temp=urlreg.exec(str)){
        strObj[count] = str.substring(index,temp.index);
        strObj[++count] = str.substring(temp.index,urlreg.lastIndex);
        count++;
        index = urlreg.lastIndex;
    }
    strObj[count] = str.substring(index);
	strObj.length = count+1;
	strObj.join = function(){
		var tempstr="";
		for(var i=0,l=this.length;i<l;i++){
			tempstr+=this[i];
		}
		return tempstr;
	}
    return strObj;
}

/*字符串是否为合法URL*/
function isURL( str ){
    var urlReg = new RegExp("^(news|telnet|nttp|file|http|ftp|https)","gi");
    return !!str.match(urlReg);
}

/*正则表达式替换有只替换一个或全部替换的开关*/
function regReplace(str,regexp,global){
    var flag = global ? "g":"";
    return str.replace(new RegExp(regexp,flag),"");
}

/*
 *符号集
 *CJK标点符号u3000-u303F CJK Symbols and Punctuation http://www.unicode.org/charts/PDF/U3000.pdf
 * 
 * */
var specialcharReg="[^\\u4e00-\\u9fa5a-zA-Z0-9]",/*特殊符号集(非中文数字a-zA-Z)之外的所有字符*/
    puncReg="(-{2})|(\\.{3})|[(\\\\)-,\\.?:;\'\"!`\\(\\)\\[\\]\\{\\}\\|\\u3000-\\u303F]",/*中英文标点符号集*/
    blankReg="\\s";/*空白字符集*/

//格式化内容按钮动作
var formatActions = {};

/*删除字符串中一个符合正则表达式的内容,自动跳过网址部分*/
formatActions.delOne = function( str,reg ){
		var strobj = splitByURL(str);
		for(var i=0,l=strobj.length;i<l;i++){
			var strComponent = strobj[i];
			if(isURL(strComponent)){//删除操作跳过URL
				continue;
			}
			var strcomponentReplaced = regReplace(strComponent,reg);
			if(strcomponentReplaced == strComponent){//没有替换到,到下一组字符串继续替换
				continue;
			}else{//替换到了
				strobj[i] = strcomponentReplaced;
				break;
			}
		}
		return strobj.join();
};

/*删除字符串中所有符合正则表达式的内容,自动跳过网址部分*/
formatActions.delAll = function( str,reg ){
		var strobj = splitByURL(str);
		for(var i=0,l=strobj.length;i<l;i++){
			var strComponent = strobj[i];
			if(isURL(strComponent)){//删除操作跳过URL
				continue;
			}
			strobj[i] = regReplace(strComponent,reg,true);
		}
		return strobj.join();
};

/*删除一个特殊字符*/
formatActions.delspecialchar = function( str ){
	return this.delOne(str,specialcharReg);
};

/*删除一个特殊标点符号*/
formatActions.delpunc = function( str ){
	return this.delOne(str,puncReg);
};

/*删除一个空白*/
formatActions.delblank = function( str ){
	return this.delOne(str,blankReg);
};

/*删除所有特殊字符*/
formatActions.delspecialcharall = function( str ){
	return this.delAll(str,specialcharReg);
};

/*删除所有标点符号*/
formatActions.delpuncall = function( str ){
	return this.delAll(str,puncReg);
};

/*删除所有空白*/
formatActions.delblankall = function( str ){
	return this.delAll(str,blankReg);
};

/*保留140个字符*/
formatActions.cutoff140 = function( str ){
	var content = document.getElementById("textContent");
	var contentVal = content.value;
	var contentValLen = smartLen(contentVal);
	if(contentValLen <= 140 ){//不需要截取
		return str;
	}
	var currentLen=0;
	var tempStr = "";
	var strobj = splitByURL(str);
	for(var i=0,l=strobj.length;i<l;i++){
		var strComponent = strobj[i];
		var strComponentLen = smartLen(strComponent);
		currentLen+=strComponentLen;
		if( currentLen > 140 ){//超过最大字数
			if(isURL(strComponent)){//URL不做分割
				break;
			}else{//字符串进行分割操作
				var maxkeep = 140 - ( currentLen - strComponentLen );//最多可以保留的字符数
				tempStr = tempStr + smartCut(strComponent,maxkeep);
				break;
			}
		}else{
			tempStr += strComponent;
		}
	}
	return tempStr;
}


//大按钮动作
function handleButtonAction( name ){
	var content = document.getElementById("textContent");
	if(name in formatActions){//格式化内容操作
		var newvalue = formatActions[name](content.value);
		content.value = newvalue;
		recountText();
	}else if( name == "post" ){//转播按钮
		/*发送微博,相当于点击转播按钮*/
		var evt = document.createEvent("MouseEvents");
		evt.initMouseEvent("click", true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
		postbtn.dispatchEvent(evt);
	}
}

//表情按钮动作
function handleEmoteAction( name ){
	var contentArea = document.getElementById("textContent");
	if(contentArea){
		contentArea.value+="/"+name;
	}
}

